package ex.hql.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ex.hql.pojo.Menu;
import ex.hql.pojo.MenuRole;
import ex.hql.pojo.RespBean;
import ex.hql.pojo.Role;
import ex.hql.service.IMenuRoleService;
import ex.hql.service.IMenuService;
import ex.hql.service.IRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program:yeb
 * @author: hql
 * @Time: 2021/8/26  15:15
 * @description: 权限组
 */
@RestController
@RequestMapping("/system/basic/permiss")
public class PermissController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IMenuRoleService menuRoleService;


    @ApiOperation(value = "获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles(){
        return roleService.list();
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/")
    public RespBean addRole(@RequestBody Role role){
        if(!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        if (roleService.save(role)) {
            return RespBean.success("添加角色成功！");
        }
        else {
            return RespBean.error("添加角色失败!");
        }
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/{rid}")
    public RespBean deleteRole(@PathVariable Integer rid){
        if(roleService.removeById(rid)){
            return RespBean.success("删除角色成功！");
        }
        else {
            return RespBean.error("删除角色失败！");
        }
    }

    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/allMenus")
    public List<Menu> getAllMenus(){
        return menuService.getAllMenus();
    }

    @ApiOperation(value = "根据角色id返回菜单id")
    @GetMapping("/{rid}")
    public List<Integer> getMenusIdByRid(@PathVariable Integer rid){
       return  menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid",rid)).stream()
               .map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/")
    public RespBean updateMenuRole(Integer  rid,Integer[] mids){
        return menuRoleService.updateMenuRole(rid,mids);
    }

}
